package com.gonsin.easycount.plugin.impl;

import com.gonsin.easycount.plugin.OuterLock;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 默认实现的锁机制
 * 如果涉及到分布式锁，应该自行实现锁的接口
 */
public class LocalLock implements OuterLock {

    private LoadingCache<String, ReadWriteLock> lockMap = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build(new CacheLoader<String, ReadWriteLock>() {
            @Override
            public ReadWriteLock load(String topic) throws Exception {
                return new ReentrantReadWriteLock();
            }
        });

    @Override
    public void readLock(String topic) {

//        log.info("读锁" + topic);
        ReadWriteLock lock = lockMap.getUnchecked(topic);
        lock.readLock().lock();
    }

    @Override
    public void readUnlock(String topic) {
//        log.info("解开读锁" + topic);
        ReadWriteLock lock = lockMap.getUnchecked(topic);
        lock.readLock().unlock();
    }

    @Override
    public void writeLock(String topic) {
//        log.info("写锁" + topic);
        ReadWriteLock lock = lockMap.getUnchecked(topic);
        lock.writeLock().lock();
    }

    @Override
    public void writeUnlock(String topic) {
//        log.info("解开写锁" + topic + " Thread : " + Thread.currentThread().getName());
        ReadWriteLock lock = lockMap.getUnchecked(topic);
        lock.writeLock().unlock();
    }
}
